package org.jeecg.modules.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * 接口相关Util
 * @Author: nc
 * @Date: 2023/2/3 14:43
 * @Description:
 */
public class ApiUtil {

    private static String key = "507a10eed8c9082b0b433690079ad3dc";


    /**
     * 请求接口获取返回的 InputStream
     * @param urlMap 在UrlUtil 中设置的map
     * @param content 页面传进来的数据map
     * @return
     * @throws Exception
     */
    public static InputStream createLink(Map<String , String> urlMap,String content) throws Exception {
        URL url = new URL( urlMap.get("url"));
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);
        conn.setDoOutput(true);
        conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(content.getBytes());
        outputStream.flush();
        outputStream.close();
        InputStream inputStream = conn.getInputStream();
        return inputStream;
    }

    /**
     * 解析返回的 InputStream
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static Map<String,String> analysisStr(InputStream inputStream) throws Exception{
        String tianapi_data = "";
        byte[] data = new byte[1024];
        StringBuilder tianapi = new StringBuilder();
        while (inputStream.read(data) != -1) {
            String t = new String(data);
            tianapi.append(t);
        }
        tianapi_data = tianapi.toString().replaceAll("\\u0000", "");
        inputStream.close();
        System.out.println(tianapi_data);
        Gson gson = new Gson();
        Map<String,String> map = new HashMap<>();
        map = gson.fromJson(tianapi_data, map.getClass());

        return map;
    }

    /**
     * 格式化查询条件
     * @param urlMap
     * @param dataMap
     * @return
     */
    public static String formatMap(Map<String , String> urlMap,Map<String , String> dataMap){
        String str = "";
        if(StringUtils.isNotEmpty(urlMap.get("val"))){
            String[] val = urlMap.get("val").split("，");
            for (int i = 0 ; i < val.length ; i++){
                str+= "&"+val[i]+"=" + dataMap.get(val[i]);
            }
        }
        String content = "key="+key+ str ;
        return content;
    }

}
